#include "project.h"
#include "usqlite.h"

int tcp_net_int(const char *port)
{

    // 创建socket
    int s_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (s_fd == -1){ 
        printf("socket创建错误\n");
        return -1;
    }

    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = inet_addr(IP_ADDR);
    addr.sin_port = htons(atoi(port));
    // bind绑定
    if (bind(s_fd, (struct sockaddr *)&addr, sizeof(addr)) == -1){   
        printf("bind error");
        return -1;
    }
    // listen监听
    if (listen(s_fd, 5)){   
        printf("listen error\n");
        return -1;
    }
    return s_fd;
}
//登录子线程处理的事情
void *login_thread(void *argv)
{   
    msg_t buf;
	while(1){
		memset(&buf,0,sizeof(msg_t));
		//监控消息队列中的 1 号消息
		msgrcv(msqid, &buf,sizeof(msg_t)-sizeof(long),1,0);
		//printf("ID:%s\n",buf.user.ID);
		//查询数据库
		if (0 == do_login_sq(&buf)){
			buf.user.flags = 1;
		}else{
			buf.user.flags = 0;
		}
		printf("登录查询后的的结果：名字：%s, 密码：%s, 是否在线：%d, flags：%d\n", 
				buf.user.ID, buf.user.password, buf.deviceonline, buf.user.flags);
		//返回结果
		buf.msgtype = 2;
		msgsnd(msqid,&buf,sizeof(msg_t)-sizeof(long),0);
	}
}
//服务器子线程处理的事情
void *handl_thread(void *argv){
   
    int accpetfd = *(int *)argv;
    long recvmsgtype,sendmsgtype;

    msg_t buf;

    //处理登录
	if(0 == recv(accpetfd, &buf, sizeof(msg_t), 0)){
		close(accpetfd);
		pthread_exit(NULL);
	}

    if (0 == do_user_exists(&buf)){//下位机登录成功
		printf("下位机登录的id：%s\n", buf.user.ID);
		//保存名字全局变量
		strcpy(ID, buf.user.ID);

		buf.user.flags = 1 ;
		buf.deviceonline = 1;
		do_change_online_sq(&buf);

        recvmsgtype = 0;
		int i = 0;
		while(buf.user.ID[i]!='\0'){
			recvmsgtype+=buf.user.ID[i];
			i++;
		}
		sendmsgtype = recvmsgtype*2;
		printf("等待的消息类型为%ld,发送的消息类型为%ld\n",recvmsgtype,sendmsgtype);
		send(accpetfd, &buf, sizeof(msg_t), 0);

        while (1){
			//等待消息
			printf("开始等待\n");
			msgrcv(msqid, &buf, sizeof(msg_t)-sizeof(long), recvmsgtype, 0);
			//发送消息
			printf("发送下位机\n");
			send(accpetfd, &buf, sizeof(msg_t),0);
			//等待结果
			memset(&buf,0,sizeof(msg_t));
			if(0 == recv(accpetfd, &buf, sizeof(msg_t),0)){
				printf("客户端[%d]断开了连接\n", accpetfd);
				close(accpetfd);
				buf.deviceonline = 0;
				do_change_online_sq(&buf);
				pthread_exit(NULL);
			}
			strcpy(buf.user.ID, ID);
			if (buf.commd == 1){
				do_query_info(&buf);
				printf("温度：%d, 湿度：%d, 光强：%d, 照明开关：%d, 风扇开关：%d, 马达开关：%d\n", 
						buf.envdata.temp, buf.envdata.hume, buf.envdata.lux,
						buf.switchset.swlight, buf.switchset.swfan, buf.switchset.swmotor);
			}else if (buf.commd == 2){//保存到数据库设置阈值
				do_change_threshold_sq(&buf);
			}else if (buf.commd == 3){//保存到数据库设置开关
				do_change_switch_sq(&buf);
			}

			//返回结果
			buf.msgtype = sendmsgtype;
			buf.user.flags = 1;
			msgsnd(msqid, &buf, sizeof(msg_t)-sizeof(long),0);
        }
    }else{
		printf("登录失败\n");
		buf.user.flags = 0;
		send(accpetfd, &buf, sizeof(msg_t), 0);
		close(accpetfd);
		pthread_exit(NULL);
    }
}